package com.example.myapp.Activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Record;
import com.example.myapp.Model.User;
import com.example.myapp.R;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;

public class AddRecord extends AppCompatActivity {
   private int flag=0;
   private String key="";
   private ImageView addrecord_images;
   private String imgpath;
    private   TextView addrecord_tel;
    private   TextView addrecord_place;
    Uri userImageUri;//切图后图片的路径
    private Uri imageUri;
    private PopupWindow pop;
  private   Button addrecord_fabu;
   private  ShapeLoadingDialog  shapeLoadingDialog;
   private   EditText addrecord_content;
    private static final int REQUEST_PERMISSION_CODE = 101;

    private ArrayList<String> ImgList=new ArrayList<>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    saveRecord(addrecord_content.getText().toString());
                    break;
                case 1:
                    saveimgRecord(addrecord_content.getText().toString());
                    break;
                default:break;

            }
        }

    };



    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.activity_add_record);
         ImageView addrecord_back=findViewById(R.id.addrecord_back);
        TextView addrecord_diushi=findViewById(R.id.addrecord_diushi);
        TextView addrecord_jiandao=findViewById(R.id.addrecord_jiandao);
        TextView addrecord_placetag=findViewById(R.id.addrecord_placetag);
         addrecord_tel=findViewById(R.id.addrecord_tel);
         addrecord_fabu=findViewById(R.id.addrecord_fabu);
         addrecord_place=findViewById(R.id.addrecord_place);
         addrecord_content=findViewById(R.id.addrecord_content);
        addrecord_images=findViewById(R.id.addrecord_images);

        //文本框监听开始，判断昵称是否被占用
        TextWatcher watcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }


            @Override
            public void afterTextChanged(Editable s) {
                if (addrecord_content.getText().toString().trim().length()>0){
                    addrecord_fabu.setBackground(getDrawable(R.drawable.fabu));
                    addrecord_fabu.setTextColor(Color.parseColor("#FFFFFF"));

                }
                else {
                    addrecord_fabu.setBackground(getDrawable(R.drawable.button));
                    addrecord_fabu.setTextColor(Color.parseColor("#828282"));
                }
            }
        };
        addrecord_content.addTextChangedListener(watcher);

        addrecord_diushi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag++;
                key="丢失";
                addrecord_placetag.setText("丢失地点：");
                addrecord_diushi.setBackground(getDrawable(R.drawable.buttonrecord));
                addrecord_diushi.setTextColor(Color.parseColor("#FFFFFF"));
                addrecord_jiandao.setTextColor(Color.parseColor("#828282"));
                addrecord_jiandao.setBackground(getDrawable(R.drawable.button));
            }
        });//选择类型
        addrecord_jiandao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag++;
                key="捡到";
                addrecord_placetag.setText("捡到地点：");
                addrecord_jiandao.setBackground(getDrawable(R.drawable.buttonrecord));
                addrecord_jiandao.setTextColor(Color.parseColor("#FFFFFF"));
                addrecord_diushi.setBackground(getDrawable(R.drawable.button));
                addrecord_diushi.setTextColor(Color.parseColor("#828282"));

            }
        });//选择类型

        addrecord_images.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                judgePermission();
                showPop();
                        }


        });//选择照片

        addrecord_fabu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addrecord_content.getText().toString().trim().length()>0&&flag>0&&addrecord_place.getText().toString().trim().length()>0){
                   if(addrecord_tel.getText().toString().trim().length()==0){
                       Toast.makeText(AddRecord.this,"请填写联系方式!",Toast.LENGTH_SHORT).show();
                       return;
                   }
                        if (imgpath==null){
                            Message message = new Message();
                            message.what = 0;
                            handler.sendMessage(message);
                        }else {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }



                }else {
                    Toast.makeText(AddRecord.this,"信息未填写完整!",Toast.LENGTH_SHORT).show();
                }


            }
        });//发布

        addrecord_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }















    private void saveimgRecord( String content ) {
        openimgLoading();
        Record record = new Record();
        record.setContent(content);
        record.setKey(key);
        record.setPlace(addrecord_place.getText().toString());
        record.setTel(addrecord_tel.getText().toString());
        final BmobFile bmobFile = new BmobFile(new File(imgpath));
        bmobFile.uploadblock(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "上传素材成功！" + e);
                    record.setImage(bmobFile);
                    //添加一对一关联，用户关联帖子
                    record.setOrderTime(System.currentTimeMillis());
                    record.setAuthor(BmobUser.getCurrentUser(User.class));
                    record.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                Log.w("aaaa", "发布帖子成功！" + s);
                                closeLoading();
                                Toast.makeText(AddRecord.this, "发布成功", Toast.LENGTH_LONG).show();
                                finish();
                            } else {
                                Log.w("aaaa", "发布帖子失败！" + e.getMessage());
                                closeLoading();
                                Toast.makeText(AddRecord.this, "发布帖子失败", Toast.LENGTH_LONG).show();
                            }
                        }
                    });

                }else {
                    Log.w("aaaa", "上传素材错误！" + e);
                }
            }
        });

    }//带照片的
    private void saveRecord( String content ) {
        openLoading();
        if (BmobUser.isLogin()) {
            Record record = new Record();
            record.setContent(content);
            record.setKey(key);
            record.setOrderTime(System.currentTimeMillis());
            record.setPlace(addrecord_place.getText().toString());
            record.setTel(addrecord_tel.getText().toString());
            //添加一对一关联，用户关联帖子
            record.setAuthor(BmobUser.getCurrentUser(User.class));
            record.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        closeLoading();
                        Log.w("aaaa", "发布帖子成功！" + s);
                        Toast.makeText(AddRecord.this,"发布成功" , Toast.LENGTH_LONG).show();
                        finish();
                    } else {
                        closeLoading();
                        Log.w("aaaa", "发布帖子失败！" + e.getMessage());
                        Toast.makeText(AddRecord.this,"发布失败" , Toast.LENGTH_LONG).show();
                    }
                }
            });
        } else {
            Log.w("aaaa", "请先登录！");
            closeLoading();
        }


    }//不带照片的

    public boolean deletefile(String filePath) {
    File file = new File(filePath);
        if (file.isFile() && file.exists()) {
        return file.delete();
         }
        return false;
    }

    // 请求权限后会在这里回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERMISSION_CODE:

                boolean allowAllPermission = false;

                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {//被拒绝授权
                        allowAllPermission = false;
                        break;
                    }
                    allowAllPermission = true;
                }
                if (allowAllPermission) {
                    //请求权限成功
                    takePhoto();
                } else {
                    Toast.makeText(AddRecord.this, "该功能需要授权方可使用", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }


    //检查权限
    private boolean checkPermission() {
        //是否有权限
        boolean haveCameraPermission = ContextCompat.checkSelfPermission(AddRecord.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;

        boolean haveWritePermission = ContextCompat.checkSelfPermission(AddRecord.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;

        return haveCameraPermission && haveWritePermission;

    }

    // 请求所需权限
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestPermissions() {
        requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
    }
    //显示选择图片上传方法方式
    private void showPop() {
        //获取写的权限
        View bottomView = View.inflate(AddRecord.this, R.layout.pop_bottom_dialog, null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);
        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                switch (view.getId()) {

                    case R.id.tv_album:
                        //相册
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                        startActivityForResult(intent, 0);//设置入口
                        break;
                    case R.id.tv_camera:

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//大于Android 6.0
                            if (!checkPermission()) { //没有或没有全部授权
                                requestPermissions(); //请求权限

                            }else {
                                takePhoto();//拍照逻辑
                            }

                        } else {

                            takePhoto();//拍照逻辑
                        }
                        break;
                    case R.id.tv_cancel:
                        //取消
//                        closePopupWindow();
                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }
    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    private void takePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            //创建一个File
            File outputImage = new File(Environment.getExternalStorageDirectory(), "out_image.jpg");
            try {
                if (outputImage.exists()) {
                    outputImage.delete();
                }
                outputImage.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (outputImage != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //如果是7.0及以上的系统使用FileProvider的方式创建一个Uri
//                    Log.e(TAG, "Build.VERSION.SDK_INT >= Build.VERSION_CODES.N");
                    imageUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", outputImage);
                    takePictureIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    takePictureIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                } else {
                    //7.0以下使用这种方式创建一个Uri
                    imageUri = Uri.fromFile(outputImage);
                }
                //将Uri传递给系统相机
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(takePictureIntent, 1);

            }
        }
    }


    //相机相应函数
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //结果码不等于取消时候

        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case 0://使用本地相册
                    if (data != null) {
                        // 得到图片的全路径
                        imageUri= data.getData();
                        showimage(imageUri);
//                        String path=imageUri.getPath();
                        imgpath=  getRealPathFromUri(AddRecord.this,imageUri);
                    //      imgpath=path.substring(4);
                        Log.w("aaaa","上传Path："+imgpath);
                        Log.w("aaaa","本机Path："+imageUri);
                    }
                    break;
                case 1:
                    //裁剪图片
                    reSizeImage(imageUri);

                    break;
                case 2:

                   showimage(imageUri);

                    break;
                default:
                    break;
            }
        }
    }


    //显示照片
    private void showimage(Uri uri){
        addrecord_images.setImageURI(uri);

    }
    //拍照原图太大需要裁剪截图
    private void reSizeImage(Uri uri) {//重新剪裁图片的大小
        Log.w("aaaa","进入切图");//剪切后的路径，用于上传
        File outputImage = new File(Environment.getExternalStorageDirectory(), "/PYB/bjt996.jpg");
        try {
            if (!outputImage.exists()) {
                outputImage.mkdirs();
            }else {
                outputImage.delete();
            }
            outputImage.createNewFile();
        }catch (Exception e){
            Log.w("aaaa","文件读写失败"+e.getMessage());
        }
        Uri putUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setType("image");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", true);//允许剪切
        intent.putExtra("scale", true);//支持缩放
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        // aspectX aspectY 是宽高的比例
//            intent.putExtra("aspectX", 4);//输出是X方向的比例
//            intent.putExtra("aspectY", 3);
        // outputX outputY 是裁剪图片宽高，切忌不要再改动下列数字，会卡死
//            intent.putExtra("outputX", 400);//输出X方向的像素
//            intent.putExtra("outputY", 300);//
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);//设置为不返回数据
        /**
         * 此方法返回的图片只能是小图片（测试为高宽160px的图片）
         * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
         */
        imageUri= getImageContentUri(AddRecord.this,outputImage);//这句话也很关键。为了得到裁剪出来的图片的Uri（直接用于显示）

        imgpath=  getRealPathFromUri(AddRecord.this,imageUri);
        Log.w("aaaa","切图后生成图片路径："+putUri.getPath());//剪切后的路径，用于上传
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//输出的Uri(默认根目录)
        startActivityForResult(intent, 2);

    }











    //    绝对路径--》》contentUri开始
    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { filePath }, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }
    //获取app做需要的权限
    protected void judgePermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            // sd卡权限
            String[] SdCardPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, SdCardPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCardPermission, 100);
            }

        }


    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    //网络加载
    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(AddRecord.this)
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //网络加载
    private  void openimgLoading(){

        shapeLoadingDialog = new ShapeLoadingDialog.Builder(AddRecord.this)
                .loadText("图片越大，上传越久哦")
                .build();
        shapeLoadingDialog.show();
    }


    //关闭网络加载
    private  void closeLoading(){

        shapeLoadingDialog.dismiss();
    }
    public void onBackPressed() {
        //此处写退向后台的处理
        finish();

    }//手机返回键

}
